package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.toChapterMetaList
import java.nio.charset.Charset

@Suppress("ClassName")
class `23Usp` : BaseBookHandler() {

    override val host: String
        get() = "www.23usp.com"

    override fun forceCharset(): Charset {
        return Charset.forName("gbk")
    }

    override fun headers(): Map<String, String> {
        return mapOf(
            "authority" to "www.23usp.com",
            "accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-language" to "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control" to "max-age=0",
            "cookie" to "Hm_lvt_f9ae6265784e39ff3e9123e3c13eee02=1672628703; SL_G_WPT_TO=zh-CN; SL_GWPT_Show_Hide_tmp=1; SL_wptGlobTipTmp=1; Hm_lpvt_f9ae6265784e39ff3e9123e3c13eee02=1672628936",
            "referer" to "https://www.23usp.com/quanbuxiaoshuo/",
            "sec-ch-ua" to """"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"""",
            "sec-ch-ua-mobile" to "?0",
            "sec-ch-ua-platform" to """"macOS"""",
            "sec-fetch-dest" to "document",
            "sec-fetch-mode" to "navigate",
            "sec-fetch-site" to "same-origin",
            "sec-fetch-user" to "?1",
            "upgrade-insecure-requests" to "1",
            "user-agent" to "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54",
        )
    }

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val title = document.select("#info > h1").text()

        val author = document.select("#info > p:nth-child(2)").text()
            .split("：")[1].trim()

        val cover = document.select("#fmimg > img").attr("src")

        return BookMetaEntity(title, url, url, author, cover)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String) =
        document.toChapterMetaList("#list > dl > dd > a", menuUrl)

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val response = get(chapterMetaEntity.url)
        val document = response.body?.bytes()?.let { parseHtml(it.toString(forceCharset())) } ?: return null
        val content = document.getElementById("content")?.bookText("  ") ?: return null
        return chapterMetaEntity.toChapterMetaEntity(content)
    }
}